package com.smsc.headend.task.engine.handler.impl.metercontrol;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.smsc.headend.module.data.enums.OperationGroup;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @author wxh
 * @date 2020/12/18
 */
@Slf4j
public class SetControlModeHandler implements TaskHandler {
    @Autowired
    TaskDAO taskDAO;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData cosemData, String actionResult) throws UDISTaskHandlerException {
        log.info("{} action result {}", atomicTask.getAtomicTaskNo(), actionResult);
        // 硬拉闸子步骤最后为 SetOriginalControlMode. 成功后返回数据到redis给web
        if (atomicTask.getGroupId().longValue() == OperationGroup.ConnectArmed.getId() && atomicTask.getOperationId().intValue() == OperationName.SetControlModeOriginal.getId()) {
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "result", "Success", 600l, Boolean.TRUE);
        }
        return 1;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}, ", message);
        if (atomicTask.getGroupId() == OperationGroup.ConnectArmed.getId().intValue()
                || atomicTask.getGroupId() == OperationGroup.Disconnect.getId().intValue()
                || atomicTask.getGroupId() == OperationGroup.CheckCdc.getId().intValue()) {
            String key = "message";
            Map<String, Object> m = JSONUtil.toBean(task.getParamJson(), Map.class);
            key = m.get("seq") != null ? Convert.toStr(m.get("seq")) : key;
            String stepOperationName = OperationName.forId(atomicTask.getOperationId()).getName();
            if (task.getIsODR()) {
                taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), key, String.format("step %s failed, [%s]", stepOperationName, message), 3600l, false);
            }
        }
        return -1;
    }
}
